<?php
/**
 * @Description: 基本信息下载
 * @Author: kzj
 * @datetime: 2023-03-28
 */
namespace App\Services\Information;

use App\Exports\TeacherInfoExport;
use App\Models\ActivityInfo;
use App\Models\System\Term;
use App\Models\Teachers;
use App\Models\Teaching\TeachingSubject;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 基本信息下载 (服务)
 */
class DownldService
{
    public function __construct()
    {

    }

    /**
     * @Description: 教师个人信息下载
     * @Author: kzj
     * @datetime: 2023-03-28
     */
    public function download($request)
    {
        if(empty($request['user_id']) || empty($request['term_id'])) {
            throw new \Exception('参数缺失！');
        }
        // 测试用
        $userId = $request['user_id'];
        $termId = $request['term_id'];
        // $userId = 0;
        // $termId = 9;

        $term = Term::where('id', $termId)->first();
        $teacher = Teachers::select('id', 'user_id', 'name', 'political', 'nation', 'mobile', 'phone_num', 'major_subject')
            ->where('user_id', $userId)
            ->where('deleted', 0)
            ->with('titleInfo', 'graduatedSchool', 'address')
            ->first();
        // dd($teacher->toArray());

        $graduatedSchoolArr = $teacher->graduatedSchool ? $teacher->graduatedSchool : [];
        $titleInfoArr = $teacher->titleInfo ? $teacher->titleInfo : [];

        $name = $teacher->name ?? '';
        // $academic = $teacher->graduatedSchool ? $teacher->graduatedSchool->academic_set[0]['selectValue'] : '';
        // $zhichen = $teacher->titleInfo ? $teacher->titleInfo->title_set[0]['selectValue'] : '';

        $academic = !empty($graduatedSchoolArr) ? $graduatedSchoolArr->academic_set[0]['selectValue'] : '';
        $zhichen = !empty($titleInfoArr) && !empty($titleInfoArr->title_set) ? $titleInfoArr->title_set[0]['selectValue'] : '';
        $political = $teacher->political ? $teacher->political_set[0]['selectValue'] : '';
        $homeAddress = $teacher->address ? $teacher->address->home_address : '';
        $postcode = $teacher->address ? $teacher->address->home_postcode : '';
        $mobile = $teacher->mobile ?? '';
        $phone = $teacher->phone_num ?? '';
        $subject = $teacher->major_subject ? str_replace("/","", $teacher->major_subject_array[0]['selectValue']) : '';

        //表格数据
        $exportData = [
            [0 => "华东理工大学附属小学 ".$term->title." 教师任职情况"],
            [0 => null, 1 => null, 2 => null, 3 => null, 4 => null, 5 => null, 6 => '编号：', 7 => null],
            [
                0 => '姓        名',
                1 => $name,
                2 => '学历',
                3 => $academic,
                4 => '职称',
                5 => $zhichen,
                6 => '党派',
                7 => $political
            ],
            [0 => '家庭地址', 1 => $homeAddress, 2 => null, 3 => '邮编', 4 => $postcode, 5 => '家庭电话', 6 => $phone],
            [0 => null, 1 => null, 2 => null, 3 => null, 4 => null, 5 => '移动电话', 6 => $mobile ],
            [0 => '任教的年级及学科',1 => $this->getTeachingInfo($userId, $termId)],
            [0 => '公开教学（日'."\r\n".'期、内容、级别）',1 => $this->getOpenInfo($userId, $termId)],
            [0 => '班级获奖情况',1 => $this->getClassAwardInfo($userId, $termId)],
            [0 => '组织学生参加教育教学活动记录',1 => $this->getThemeInfo($userId, $termId)],
            [0 => '指导课外活动运动队情况',1 => $this->getPracticeInfo($userId, $termId)],
            [0 => '教育教学研究及教育科研成果情况（详细填写日期）',1 => $this->getResearchInfo($userId, $termId)],
            [0 => '培养、指导教师情况 ',1 => $this->getImportantInfo($userId, $termId)],
            [0 => '奖惩情况（填写发奖单位与日期）',1 => $this->getAwardInfo($userId, $termId)],
            [0 => null, 1 => null, 2 => null, 3 => null, 4 => null, 5 => '填写日期：', 6 => '      年      月      日'],
        ];

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new TeacherInfoExport($exportData), $fileName, 'excel');

        $result = [
            'file_name' => $fileName,
            'show_name' => $term->title . '_' . $subject . '_' . $name . '_' .date('YmdHis') . '.xlsx',
        ];

        return $result;
    }

    //任教的年级及学科
    public function getTeachingInfo($userId, $termId)
    {
        $info = TeachingSubject::where('data_version_id', $termId)
            ->where('user_id', $userId)
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                // $classes = [];
                // foreach($i['class_set'] as $class) {
                //     $classes[] = $class['selectValue'];
                // }

                // $result .= $i->subject_set[0]["selectValue"] . " " . $i->grade_set[0]["selectValue"] . "(" . $i->class_set['classes']  . ") " . (int)$i->class_hour . "课时" . "\r\n";
                if($i->subject_set && is_array($i->subject_set)) {
                    $result .= $i->subject_set[0]["selectValue"] . " ";
                }
                if($i->grade_set && is_array($i->grade_set)) {
                    $result .= $i->grade_set["grades"];
                }
                if($i->class_set && is_array($i->class_set)) {
                    $result .= "(" . $i->class_set['classes']  . ") ";
                }
                $result .= (int)$i->class_hour . "课时" . "\r\n";
            }

            return $result;
        } else {
            return "";
        }
    }

    //公开教学
    public function getOpenInfo($userId, $termId)
    {
        $info = ActivityInfo::select('id', 'name', 'date', 'begin_date', 'level', 'data_version_id', 'creator_id', 'activity_category')
            ->whereIn('activity_category', ['TEARRESEARCH_OPEN_TABLE', 'EW_CLASS_MEETING_TABLE'])
            ->where('data_version_id', $termId)
            ->where(function($q) use($userId){
                $q->orWhereHas("participants", function($query) use($userId) {
                    $query->where("user_id", $userId);
                })
                ->orWhere('creator_id', $userId);
            })
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                $result .= $i->date ?? $i->begin_date;
                $result .= " " . $i->name . " ";
                if($i->level_array && is_array($i->level_array)) {
                    $result .= $i->level_array[0]["selectValue"] . "\r\n";
                } else {
                    $result .= "\r\n";
                }
            }

            return $result;
        } else {
            return "";
        }
    }

    // 班级获奖情况
    public function getClassAwardInfo($userId, $termId)
    {
        $info = ActivityInfo::select('id', 'name', 'begin_date', 'end_date', 'date', 'level', 'category', 'data_version_id', 'creator_id', 'activity_category')
            ->where('activity_category', 'TEACHER_AWARD_TABLE')
            ->whereRaw(" JSON_EXTRACT(`category`,'$[0].optionId') = 148 ")
            ->where('data_version_id', $termId)
            ->where(function($q) use($userId){
                $q->orWhereHas("participants", function($query) use($userId) {
                    $query->where("user_id", $userId);
                })
                ->orWhere('creator_id', $userId);
            })
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                $result .= $i->end_date ?? $i->date . " " . $i->name . " ";
                if($i->level_array && is_array($i->level_array)) {
                    $result .= $i->level_array[0]["selectValue"] . "\r\n";
                } else {
                    $result .= "\r\n";
                }
            }

            return $result;
        } else {
            return "";
        }
    }

    // 组织学生参加教育教学活动记录
    public function getThemeInfo($userId, $termId)
    {
        $info = ActivityInfo::select('id', 'name', 'date', 'level', 'data_version_id', 'creator_id', 'activity_category')
            ->where('activity_category', 'EW_THEME_ACTIVITY_TABLE')
            ->where('data_version_id', $termId)
            ->where(function($q) use($userId){
                $q->orWhereHas("participants", function($query) use($userId) {
                    $query->where("user_id", $userId);
                })
                ->orWhere('creator_id', $userId);
            })
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                $result .= $i->date . " " . $i->name . " ";
                if($i->level_array && is_array($i->level_array)) {
                    $result .= $i->level_array[0]["selectValue"] . "\r\n";
                } else {
                    $result .= "\r\n";
                }
            }

            return $result;
        } else {
            return "";
        }
    }

    // 指导课外活动运动队情况
    public function getPracticeInfo($userId, $termId)
    {
        $info = ActivityInfo::select('id', 'name', 'begin_date', 'end_date', 'level', 'data_version_id', 'creator_id', 'activity_category', 'pubications_publish_type', 'course')
            ->where('activity_category', 'TEARRESEARCH_DEVELOP_SUBJECT_TABLE')
            ->where('data_version_id', $termId)
            ->where(function($q) use($userId){
                $q->orWhereHas("participants", function($query) use($userId) {
                    $query->where("user_id", $userId);
                })
                ->orWhere('creator_id', $userId);
            })
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                $result .= $i->name . "\r\n";
                // $result .= $i->begin_date . " ~ " . $i->end_date . " " . $i->name . " ";
                // if($i->level_array && is_array($i->level_array)) {
                //     $result .= $i->level_array[0]["selectValue"] . "\r\n";
                // }
                // if($i->publish_type_set && is_array($i->publish_type_set)) {
                //     $result .= $i->publish_type_set[0]["itemname"] . " ";
                // }
                // if($i->course_set && is_array($i->course_set)) {
                //     $result .= $i->course_set[0]["selectValue"];
                // }
                // $result .= "\r\n";
            }

            return $result;
        } else {
            return "";
        }
    }

    // 教育教学研究、教育科研成果情况（详细填写日期）
    public function getResearchInfo($userId, $termId)
    {
        $info = ActivityInfo::select('id', 'name', 'begin_date', 'end_date', 'level', 'data_version_id', 'creator_id', 'activity_category')
            ->whereIn('activity_category', ['TEARRESEARCH_PUBLISH_TABLE', 'TEARRESEARCH_SUBJECT_STUDY_TABLE'])
            ->where('data_version_id', $termId)
            ->where(function($q) use($userId){
                $q->orWhereHas("participants", function($query) use($userId) {
                    $query->where("user_id", $userId);
                })
                ->orWhere('creator_id', $userId);
            })
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                $result .= $i->begin_date . " " . $i->name . " ";
                if($i->level_array && is_array($i->level_array)) {
                    $result .= $i->level_array[0]["selectValue"] . "\r\n";
                } else {
                    $result .= "\r\n";
                }
            }

            return $result;
        } else {
            return "";
        }

    }

    // 培养、指导教师情况
    public function getImportantInfo($userId, $termId)
    {
        $info = ActivityInfo::select('id', 'name', 'date', 'begin_date', 'end_date', 'level', 'data_version_id', 'creator_id', 'activity_category')
            ->where('activity_category', 'IMPORTANTWORK_TEACHING_SITUATION_TABLE')
            ->where('data_version_id', $termId)
            ->where(function($q) use($userId){
                $q->orWhereHas("participants", function($query) use($userId) {
                    $query->where("user_id", $userId);
                })
                ->orWhere('creator_id', $userId);
            })
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                if($i->begin_date && $i->end_date) {
                    $result .= $i->begin_date . " ~ " . $i->end_date . " " . $i->name . " ";
                    if($i->level_array && is_array($i->level_array)) {
                        $result .= $i->level_array[0]["selectValue"] . "\r\n";
                    } else {
                        $result .= "\r\n";
                    }
                } else {
                    $result .= $i->end_date . " " . $i->name . " ";
                    if($i->level_array && is_array($i->level_array)) {
                        $result .= $i->level_array[0]["selectValue"] . "\r\n";
                    } else {
                        $result .= "\r\n";
                    }
                }
            }

            return $result;
        } else {
            return "";
        }
    }

    // 奖惩情况（填写发奖单位与日期）
    public function getAwardInfo($userId, $termId)
    {
        $info = ActivityInfo::select('id', 'name', 'date', 'begin_date', 'end_date', 'award_from', 'level', 'category', 'data_version_id', 'creator_id', 'activity_category')
            ->where('activity_category', 'TEACHER_AWARD_TABLE')
            ->where('data_version_id', $termId)
            ->whereRaw(" JSON_EXTRACT(`category`,'$[0].optionId') != 148 ")
            ->where(function($q) use($userId){
                $q->orWhereHas("participants", function($query) use($userId) {
                    $query->where("user_id", $userId);
                })
                ->orWhere('creator_id', $userId);
            })
            ->where('deleted', 0)
            ->get();

        if($info->count()) {
            $result = "";
            foreach($info as $i) {
                $endDate = $i->end_date ?? $i->date;
                // $date = $i->begin_date ? $i->begin_date . " ~ " . $endDate : $endDate;
                $result .= $endDate . " " . $i->award_from . " " . $i->name . " ";
                if($i->level_array && is_array($i->level_array)) {
                    $result .= $i->level_array[0]["selectValue"] . "\r\n";
                } else {
                    $result .= "\r\n";
                }
            }

            return $result;
        } else {
            return "";
        }
    }

}
